package com.example.backgroundmanger.interceptor;

import com.alibaba.fastjson2.JSON;
import com.example.backgroundmanger.commons.JwtUtil;
import com.example.backgroundmanger.commons.Result;
import com.example.backgroundmanger.entity.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT拦截器
 * 用于验证请求中的JWT token
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        log.info("JWT拦截器 - 请求路径: {}", requestURI);

        // 不需要token验证的路径
        if (isExcludedPath(requestURI)) {
            log.info("JWT拦截器 - 跳过验证路径: {}", requestURI);
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            // 如果Authorization头为空，尝试从X-Token头获取
            token = request.getHeader("X-Token");
        }

        if (!StringUtils.hasText(token)) {
            log.warn("JWT拦截器 - 未找到token，路径: {}", requestURI);
            writeErrorResponse(response, 401, "未授权，请先登录");
            return false;
        }

        try {
            // 解析token
            User user = jwtUtil.parseToken(token, User.class);
            if (user == null) {
                log.warn("JWT拦截器 - token解析失败，路径: {}", requestURI);
                writeErrorResponse(response, 401, "登录身份信息已过期");
                return false;
            }

            // 将用户信息存储到request中，后续控制器可以直接使用
            request.setAttribute("currentUser", user);
            log.info("JWT拦截器 - token验证成功，用户: {}", user.getUsername());
            return true;

        } catch (Exception e) {
            log.error("JWT拦截器 - token验证异常，路径: {}, 错误: {}", requestURI, e.getMessage());
            writeErrorResponse(response, 401, "登录身份信息已过期");
            return false;
        }
    }

    /**
     * 判断是否为不需要token验证的路径
     */
    private boolean isExcludedPath(String path) {
        // 不需要token验证的路径列表
        String[] excludePaths = {
            "/user/login",
            "/user/register",
            "/avatar/**",  // 头像访问路径
            "/swagger-ui/**",
            "/v3/api-docs/**",
            "/swagger-resources/**",
            "/webjars/**",
            "/doc.html",
            "/favicon.ico"
        };

        for (String excludePath : excludePaths) {
            if (excludePath.endsWith("/**")) {
                // 处理通配符路径
                String basePath = excludePath.substring(0, excludePath.length() - 3);
                if (path.startsWith(basePath)) {
                    return true;
                }
            } else if (path.equals(excludePath)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 写入错误响应
     */
    private void writeErrorResponse(HttpServletResponse response, int code, String message) throws Exception {
        response.setStatus(200); // HTTP状态码设为200，业务状态码在响应体中
        response.setContentType("application/json;charset=utf-8");
        
        Result<?> result = Result.error(code, message);
        String jsonResponse = JSON.toJSONString(result);
        
        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }
} 